package com.kevin.ymqquan.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kevin.ymqquan.R;
import com.kevin.ymqquan.activity.ConClubActiveActivity.ActiveAsynTask;
import com.kevin.ymqquan.application.App;
import com.kevin.ymqquan.constants.Constants;
import com.kevin.ymqquan.custom.CustomToast;
import com.kevin.ymqquan.httppost.Helper;
import com.kevin.ymqquan.httppost.HttpPostService;

public class CourseDDetailActivity extends Activity {

	private String isJoin;
	private String activeId;
	private String isOver;
	private String position;
	private String courseId;

	private App application;

	private Dialog dialog;

	private TextView tv_active_detail_activename;
	private TextView tv_active_detail_activetime_right;
	private TextView tv_active_detail_venuename_right;
	private TextView tv_active_detail_remark_right;
	private Button btn_active_detail_apply;
	private ImageView iv_active_detail_back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_coursed_detail);

		Intent i = getIntent();

		isJoin = i.getStringExtra("isJoin");
		isOver = i.getStringExtra("isOver");
		courseId = i.getStringExtra("courseId");
		String activeName = i.getStringExtra("activeName");
		String activeTime = i.getStringExtra("activeTime");
		String venueName = i.getStringExtra("venueName");
		String remark = i.getStringExtra("remark");
		String position = i.getStringExtra("position");

		init();// 初始化
		Log.i("kevinlog", isJoin + "-" + isJoin + "-" + isOver + "-" + activeId
				+ "-" + activeName + "-" + activeTime + "-"  + "-"
				+ venueName + "-"  + "-" + remark + "-" + position);

		tv_active_detail_activename.setText(activeName);
		tv_active_detail_activetime_right.setText(activeTime);
		tv_active_detail_venuename_right.setText(venueName);
		tv_active_detail_remark_right.setText(remark);
		addListen();
	}

	private void addListen() {
		if ("1".equals(isOver)) {
			btn_active_detail_apply.setText("活动已经结束");
			btn_active_detail_apply.setEnabled(false);
			btn_active_detail_apply.setBackgroundColor(Color.GRAY);
		} else {
			if ("0".equals(isJoin)) {
				btn_active_detail_apply.setText("立即报名");
				btn_active_detail_apply.setBackgroundColor(getResources().getColor(R.color.software_textColor_unselected));
				btn_active_detail_apply
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								if (Helper.checkConnection(CourseDDetailActivity.this)) {
									dialog = CustomToast.createLoadingDialog(CourseDDetailActivity.this,
											"数据获取中...");
									dialog.setCancelable(true);
									dialog.show();
									ApplyReasonAsyTask policyTask = new ApplyReasonAsyTask();
									policyTask.execute();

								} else {
									CustomToast.CustomActivityToast(CourseDDetailActivity.this,
											"网络连接异常，请检查您的网络", -80);
								}
								// startActivity(i);
								// ActiveDetailActivity.this.finish();
							}
						});
			} else {
				btn_active_detail_apply.setText("退出活动");
				btn_active_detail_apply.setBackgroundColor(Color.RED);
				btn_active_detail_apply
						.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								outActive();
							}
						});
				// btn_active_detail_apply.setEnabled(false);
				// btn_active_detail_apply.setBackgroundColor(Color.GRAY);
			}

		}
	}

	protected void outActive() {
		// TODO Auto-generated method stub
		LayoutInflater inflaterDl = LayoutInflater
				.from(CourseDDetailActivity.this);
		LinearLayout inflate = (LinearLayout) inflaterDl.inflate(
				R.layout.activity_logout_dialog, null);
		final Dialog dialog = new AlertDialog.Builder(CourseDDetailActivity.this)
				.create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		dialog.getWindow().setContentView(inflate);
		TextView tv_setting_update_dialog_title = (TextView) inflate
				.findViewById(R.id.tv_logout_dialog_title);
		tv_setting_update_dialog_title.setText("确定要退出活动吗？");
		TextView tv_dialog_left_btn = (TextView) inflate
				.findViewById(R.id.tv_dialog_left_btn);
		tv_dialog_left_btn.setText("确认");
		TextView tv_dialog_right_btn = (TextView) inflate
				.findViewById(R.id.tv_dialog_right_btn);
		tv_dialog_right_btn.setText("取消");

		RelativeLayout rl_setting_update_dialog_cancel = (RelativeLayout) inflate
				.findViewById(R.id.ll_logout_dialog_cancel);
		RelativeLayout rl_setting_update_dialog_ensure = (RelativeLayout) inflate
				.findViewById(R.id.ll_logout_dialog_ok);
		rl_setting_update_dialog_ensure
				.setOnClickListener(new View.OnClickListener() {

					@SuppressWarnings("null")
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						// 显示下载对话框
						try {
							sureOutActive();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});

		rl_setting_update_dialog_cancel
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});

	}

	protected void sureOutActive() {
		// TODO Auto-generated method stub
		if (Helper.checkConnection(CourseDDetailActivity.this)) {
			dialog = CustomToast.createLoadingDialog(CourseDDetailActivity.this,
					"数据获取中...");
			dialog.setCancelable(true);
			dialog.show();
			OutActiveTask policyTask = new OutActiveTask();
			policyTask.execute();

		} else {
			CustomToast.CustomActivityToast(CourseDDetailActivity.this,
					"网络连接异常，请检查您的网络", -80);
		}
	}

	private void init() {
		// TODO Auto-generated method stub
		application = (App) getApplication();
		tv_active_detail_activename = (TextView) findViewById(R.id.tv_active_detail_activename);
		tv_active_detail_activetime_right = (TextView) findViewById(R.id.tv_active_detail_activetime_right);
		tv_active_detail_venuename_right = (TextView) findViewById(R.id.tv_active_detail_venuename_right);
		tv_active_detail_remark_right = (TextView) findViewById(R.id.tv_active_detail_remark_right);
		btn_active_detail_apply = (Button) findViewById(R.id.btn_active_detail_apply);
		iv_active_detail_back = (ImageView) findViewById(R.id.iv_active_detail_back);

		iv_active_detail_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				backIntent();
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			isJoin = data.getStringExtra("isJoin");
			addListen();
			// Log.i("kevinlog", isJoin);
			// if ("0".equals(isJoin)) {
			// btn_active_detail_apply.setText("立即报名");
			// } else {
			// btn_active_detail_apply.setText("已报名");
			// btn_active_detail_apply.setEnabled(false);
			// btn_active_detail_apply.setBackgroundColor(Color.GRAY);
			// }
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			backIntent();
		}
		return false;
	}

	private void backIntent() {
		Intent intent = new Intent(CourseDDetailActivity.this,
				ClubActiveActivity.class);
		setResult(Integer.parseInt(isJoin), intent);
		CourseDDetailActivity.this.finish();
	}

	class OutActiveTask extends AsyncTask<String, Object, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			// sendReplyText = Base64.encodeToString(sendReplyText.getBytes(),
			// Base64.NO_WRAP);

			String param = "{\"method\":\"courseDQuit\",\"userId\":\""
					+ application.userId + "\",\"activeId\":\"" + courseId
					+ "\"}";
			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i("kevinlog", param);
			Log.i("kevinlog", replyList);
			return replyList;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Log.i("kevinlog", result);
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(result);
				String resultType = jsonObject.getString("status");
				if ("0".equals(resultType)) {

					isJoin = "0";
					addListen();
					CustomToast.CustomActivityToast(CourseDDetailActivity.this,
							"退出活动成功", 0);
					// ActiveApplyActivity.this.finish();
				} else if ("100".equals(resultType)) {
					CustomToast.CustomActivityToast(CourseDDetailActivity.this,
							"服务器异常，请稍后重试", 0);
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Log.i("kevinlog", "error");
				e.printStackTrace();
			}

			dialog.dismiss();
		}

	}
	
	
	class ApplyReasonAsyTask extends AsyncTask<String, Object, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			String param = "{\"method\":\"courseDSignUp\",\"userId\":\""
					+ application.userId + "\",\"activeId\":\"" + courseId
					+ "\"}";
			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i("kevinlog", param);
			Log.i("kevinlog", replyList);
			return replyList;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// Log.i("kevinlog", result);
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(result);
				String resultType = jsonObject.getString("status");
				if ("0".equals(resultType)) {
					CustomToast.CustomActivityToast(CourseDDetailActivity.this,
							"课表报名成功", 0);
					isJoin = "1";
//					backIntent();
					addListen();
					// ActiveApplyActivity.this.finish();
				} else if ("100".equals(resultType)) {
					CustomToast.CustomActivityToast(CourseDDetailActivity.this,
							"服务器异常，请稍后重试", 0);
				}  else if ("200".equals(resultType)) {
					CustomToast.CustomActivityToast(CourseDDetailActivity.this,
							"已报名该课表，无需重新报名", 0);
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Log.i("kevinlog", "error");
				e.printStackTrace();
			}

			dialog.dismiss();
		}

	}
	
}
